﻿// ----------------------------------------------------------------------- 
//  <copyright file="StorageProvider.cs" company="DirecTV"> 
//      Copyright (c) DirecTV. All rights reserved. 
//  </copyright> 
// -----------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Windows.Storage;
using Newtonsoft.Json;

namespace PhoneMap.Common
{
    public class StorageProvider
    {
        public const string LISTFRIENDS = "LISTFRIENDS";
        public const string FACEBOOKDATA = "FACEBOOKDATA";
        public const string BackgroudInfos = "BackgroudInfo";
        /// <summary>
        ///     <see cref="IStorageProvider.SaveObjectsAsync{T}(T,string)"/>
        /// </summary>
        public static async Task<bool> SaveObjectsAsync<T>(T sourceData, string targetFileName)
        {
            var isf = IsolatedStorageFile.GetUserStoreForApplication();
            if (await FileExistsAsync(targetFileName).ConfigureAwait(false))
                isf.DeleteFile(targetFileName);
            var dataString = JsonConvert.SerializeObject(sourceData);

            IsolatedStorageFile data = IsolatedStorageFile.GetUserStoreForApplication();

            using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(targetFileName, FileMode.OpenOrCreate, data))
            {
                StreamWriter writer = new StreamWriter(fs);
                writer.Write(dataString);
                writer.Close();
            };
            return true;
        }
        /// <summary>
        ///     <see cref="IStorageProvider.RestoreObjectsAsync{T}(string)"/>
        /// </summary>
        public static async Task<T> RestoreObjectsAsync<T>(string fileName)
        {
            var isf = IsolatedStorageFile.GetUserStoreForApplication();
            if (isf.FileExists(fileName))
            {
                using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf))
                {
                    StreamReader reader = new StreamReader(fs);
                    var theData = reader.ReadToEnd();
                    reader.Close();
                    if (!string.IsNullOrEmpty(theData))
                    {
                        var data = JsonConvert.DeserializeObject(theData, typeof(T));
                        return data != null ? (T)data : default(T);
                    }
                };
            }

            return default(T);

        }

        /// <summary>
        ///     <see cref="IStorageProvider.FileExistsAsync(string)"/>
        /// </summary>
        public static async Task<bool> FileExistsAsync(string fileName)
        {
            try
            {
                await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                return true;
            }
            catch (FileNotFoundException)
            {
                return false;
            }
        }

        /// <summary>
        ///     <see cref="IStorageProvider.DeleteFileAsync(string)"/>
        /// </summary>
        public static async Task<bool> DeleteFileAsync(string fileName)
        {
            try
            {
                var isf = IsolatedStorageFile.GetUserStoreForApplication();
                if (await FileExistsAsync(fileName))
                {
                    isf.DeleteFile(fileName);
                    return true;
                }
                else
                    return false;
            }
            catch (FileNotFoundException)
            {
                return false;
            }
        }

        /// <summary>
        ///     <see cref="IStorageProvider.DeleteData()"/>
        /// </summary>
        public static bool DeleteData()
        {
            var data = IsolatedStorageFile.GetUserStoreForApplication();
            try
            {
                data.Remove();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        ///     <see cref="IStorageProvider.SaveToLocal(string,object)"/>
        /// </summary>
        public static void SaveToLocal(string key, object value)
        {
            var isf = IsolatedStorageSettings.ApplicationSettings;

            if (!isf.Contains(key))
            {
                isf.Add(key, value);
            }
            else
            {
                isf[key] = value;
            }

            isf.Save();
        }

        /// <summary>
        ///     <see cref="IStorageProvider.LoadFromLocal(string)"/>
        /// </summary>
        public static object LoadFromLocal(string key)
        {
            Debug.WriteLine("LoadFromLocal=" + key);
            var isf = IsolatedStorageSettings.ApplicationSettings;
            if (isf.Contains(key))
            {
                return isf[key];
            }

            return default(object);
        }
    }
}
